Angular 2 : System.import() : Not working with full path

Sandip - Full Stack Developer

I am using below two different code to import a file runtime, one of them is working fine while other one throw error.

Working:

 System.import('../../FileName.ts').then(classObj => {          
        console.log(classObj);            
 });

Not Working:

 System.import('App/Models/FileName.ts').then(classObj => {          
        console.log(classObj);            
 });

It throw below error :

Can not find module 'App/Models/FileName.ts'

File Structure in which code is written and i also trying to import file from same structure:

(1) Code : ActivityModel.ts (2) Importing : ApplicationModel.ts

enter image description here

Any one can help me to resolve above full path consideration issue.

Darshita

First of all, make sure you have latest version of webpack installed.Then you can try with following changes :

In webpack.config.js file change the following piece of code,

resolve: {
        extensions: ['.ts', '.js', 'css'],
        "modules": [
            "./node_modules",
            "content"
        ]
    },

And

 output: {
            path: path.resolve(__dirname, 'dist'),
            filename: '[name].js',
            publicPath: 'dist/',
        }

In .ts file change,

System.import('horizontal/models/FileName.ts').then(classObj => {          
        console.log(classObj);            
 });
  • The resolver is used to load files relative to the app root and by resolving content folder in webpack.config.js, file within that folder can be accessed by absolute path as shown above.

    (Now,path like content/horizontal/models/FileName.ts won't work)

  • The bundle file of FileName.ts will be created in dist folder and will be loaded in the browser dynamically.Webpack will throw an error in the browser, that it cannot load chunk 0 or something. This is because, it tries to load the other files relative to the your HTML file and not relative to the first JavaScript file you loaded via the script tag.

    To migrate this, you have to add a publicPath to your Webpack config.

Hope,It wil help!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related